package springbootchapter03_03.service;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import springbootchapter03_03.Repository.CommentRepository;
import springbootchapter03_03.entity.Comment;


import java.util.List;

@Service
public class CommentService {
    @Autowired
    private CommentRepository commentRepository;

    public List<Comment> findAll() {
            return commentRepository.findAll();

        }
        public Comment selectById(Integer id){
            return commentRepository.findById(id).get();
    }
    public void delById(Integer id){
        commentRepository.deleteById(id);
    }
    public Comment addComment(String content, String author, Integer aId){
        Comment comment =new Comment();
        comment.setAuthor(author);
        comment.setContent(content);
        comment.setAId(aId);
        return commentRepository.save(comment);

    }
    public List<Comment> selectAllSortByAId(){
        return commentRepository.findAll(Sort.by(Sort.Direction.ASC,"aId"));//通过aId升序
    }

    public List<Comment> selectAllPage(int page, int size){
        Pageable pageable = PageRequest.of(page,size);
        return commentRepository.findAll(pageable).getContent();
    }

    public List<Comment> selectByExample(String author){
        Comment comment=new Comment();
        comment.setAuthor(author);
        Example<Comment> commentExample = Example.of(comment);
        return commentRepository.findAll(commentExample);
    }
}
